﻿<template>
  <s-layout :title="pageTitle">
    <su-sticky bgColor="#fff">
      <su-tabs
          :list="tabMaps"
          :scrollable="false"
          @change="onTabsChange"
          :current="state.currentTab"
      ></su-tabs>
    </su-sticky>

    <s-empty
        v-if="state.pagination.total === 0"
        icon="https://picture-1326598115.cos.ap-nanjing.myqcloud.com/2025/09/2489e93becde3c4254a1d5cda65818f8fcorder-empty.png"
        text="暂无订单"
    ></s-empty>

    <view v-if="state.pagination.total > 0">
      <view
          class="bg-white order-list-card-box ss-r-10 ss-m-t-14 ss-m-20"
          v-for="order in state.pagination.data"
          :key="order.systemOrderId"
      >
        <!-- 订单头部 -->
        <view class="order-card-header ss-flex ss-col-center ss-row-between ss-p-x-20">
          <view class="order-no">订单号：{{ order.orderSn }}</view>
          <view
              class="order-state ss-font-24 ml-auto"
              :class="formatOrderColor(order.orderStatus)"
          >
            <text>{{ getOrderStatusName(order.orderStatus) }}</text>
          </view>
        </view>

        <!-- 门店信息 -->
        <view class="store-info ss-p-x-20 ss-p-y-10">
          <view class="store-name">{{ order.shopName || '门店' }}</view>
          <view class="order-time">{{ formatTime(order.createTime) }}</view>
        </view>

        <!-- 商品列表 - 固定高度可滚动 -->
        <scroll-view
            v-if="getOrderProducts(order).length > 0"
            class="goods-scroll-list"
            scroll-y
            :show-scrollbar="false"
        >
          <view class="border-bottom" v-for="(item, index) in getOrderProducts(order)" :key="index">
            <view class="goods-item ss-flex ss-p-x-20 ss-p-y-20">
              <image class="goods-img" :src="getProductImage(item)" mode="aspectFill"></image>
              <view class="goods-content ss-flex-1 ss-m-l-20">
                <view class="goods-title ss-line-2">{{ getProductName(item) }}</view>
                <view class="goods-spec ss-m-t-10" v-if="getProductSpec(item)">{{ getProductSpec(item) }}</view>
                <view class="goods-footer ss-flex ss-col-center ss-row-between ss-m-t-10">
                  <view class="goods-price">¥{{ formatPrice(getProductPrice(item)) }}</view>
                  <view class="goods-num">x{{ getProductCount(item) }}</view>
                </view>
              </view>
            </view>
          </view>
        </scroll-view>
        <view v-else class="empty-products ss-p-x-20 ss-p-y-30">
          <text class="empty-text">暂无商品信息</text>
        </view>

        <!-- 订单金额 -->
        <view class="pay-box ss-m-t-30 ss-flex ss-row-right ss-p-r-20">
          <view class="ss-flex ss-col-center">
            <view class="discounts-title pay-color">共{{ getTotalCount(order.products) }}件商品，</view>
            <view class="discounts-title pay-color">实付：</view>
            <view class="discounts-money pay-color">￥{{ formatPrice(order.payAmount) }}</view>
          </view>
        </view>

        <!-- 订单操作按钮 -->
        <view class="order-card-footer ss-flex ss-col-center ss-p-x-20">
          <view class="ss-flex ss-col-center ml-auto">
            <button
                class="apply-btn ss-reset-button"
                @tap.stop="onOrderDetail(order.orderId)"
            >
              查看详情
            </button>
            <button
                v-if="order.orderStatus === 0"
                class="tool-btn ss-reset-button ui-BG-Main-Gradient"
                @tap.stop="onPay(order)"
            >
              去支付
            </button>
          </view>
        </view>
      </view>
    </view>

    <!-- 加载更多 -->
    <uni-load-more
        v-if="state.pagination.total > 0"
        :status="state.loadStatus"
        :content-text="{
          contentdown: '上拉加载更多',
          contentrefresh: '加载中',
          contentnomore: '没有更多了',
        }"
        @tap="loadmore"
    />
  </s-layout>
</template>

<script setup>
import { reactive, computed } from 'vue';
import { onLoad, onReachBottom } from '@dcloudio/uni-app';
import sheep from '@/sheep';

// 订单状态标签
const tabMaps = [
  { name: '全部', value: 'all' },
  { name: '待支付', value: '0' },
  { name: '待取餐', value: '1' },
  { name: '已完成', value: '3' },
];

const state = reactive({
  currentTab: 0,
  pagination: {
    data: [],
    current_page: 1,
    total: 0,
    last_page: 1,
  },
  loadStatus: '',
  restaurantId: null, // 餐厅ID
  brandOt: null, // 品牌类型（null表示查询所有餐厅）
  brandName: '', // 品牌名称
});

// 动态页面标题
const pageTitle = computed(() => {
  if (state.brandName && state.brandName !== '全部餐厅') {
    return `${state.brandName} - 我的订单`;
  }
  return '我的点餐订单';
});

onLoad(async (options) => {
  console.log('【订单列表】onLoad 接收的参数:', options);

  // 接收餐厅ID
  if (options.restaurantId) {
    state.restaurantId = parseInt(options.restaurantId);
    console.log('【订单列表】接收到餐厅ID:', state.restaurantId);
  }

  // 接收品牌参数
  if (options.ot) {
    state.brandOt = parseInt(options.ot);
  }
  if (options.cateringName) {
    state.brandName = options.cateringName;
  }

  // 接收门店ID（从上一页传入），优先使用这个shopId
  if (options.shopId) {
    console.log('【订单列表】从参数接收到 shopId:', options.shopId);
    const store = sheep.$store('catering').storeInfo || {};
    sheep.$store('catering').setStore({ ...store, shopId: options.shopId });
  }

  const cateringStore = sheep.$store('catering');
  console.log('【订单列表】当前 storeInfo:', cateringStore.storeInfo);
  console.log('【订单列表】筛选条件 - 餐厅ID:', state.restaurantId, 'ot:', state.brandOt, 'shopId:', cateringStore.storeInfo?.shopId);

  // 显示加载状态
  state.loadStatus = 'loading';
  await getOrderList();
});

// 获取订单列表
async function getOrderList(page = 1, loadMore = false) {
  state.loadStatus = 'loading';

  const tabValue = tabMaps[state.currentTab].value;
  const orderStatus = tabValue === 'all' ? null : tabValue;

  try {
    const cateringStore = sheep.$store('catering');
    // const shopId = cateringStore.storeInfo?.shopId || cateringStore.storeInfo?.id || '';

    // 确定使用哪个餐厅标识：优先使用 restaurantId，其次使用 ot
    const orderType = state.restaurantId || state.brandOt;

    console.log('【订单列表】准备请求订单列表');
    console.log('  - 餐厅ID:', state.restaurantId);
    console.log('  - 品牌类型(ot):', state.brandOt);
    console.log('  - 最终使用的orderType:', orderType || '全部餐厅');
    // console.log('  - 门店ID:', shopId || '全部门店');
    console.log('  - storeInfo:', cateringStore.storeInfo);

    const params = {
      pageIndex: page,
      pageSize: 10,
      orderStatus: orderStatus
    };

    // 只有指定了餐厅时才传递 orderType（null时查询所有餐厅订单）
    if (orderType) {
      params.orderType = orderType;
    }

    // 只有当shopId有值时才传递（避免后端收到空字符串）
    // if (shopId) {
    //   params.shopId = shopId;
    // }

    console.log('【订单列表】最终请求参数:', params);
    const res = await sheep.$api.catering.getOrderList(params);

    console.log('订单列表响应:', res);

    if (res.code === 200 && res.data) {
      const newData = res.data.list || [];

      if (loadMore) {
        state.pagination.data = [...state.pagination.data, ...newData];
      } else {
        state.pagination.data = newData;
      }

      state.pagination.current_page = page;
      state.pagination.total = res.data.total || 0;
      state.pagination.last_page = res.data.pages || Math.ceil(state.pagination.total / 10);

      // 更新加载状态
      if (newData.length === 0 && page === 1) {
        state.loadStatus = ''; // 第一页无数据，不显示加载更多
      } else if (state.pagination.current_page >= state.pagination.last_page) {
        state.loadStatus = 'noMore';
      } else {
        state.loadStatus = 'more';
      }
    } else {
      // 接口返回失败
      if (!loadMore) {
        state.pagination.data = [];
        state.pagination.total = 0;
      }
      state.loadStatus = 'noMore';

      // 显示错误提示
      if (res.msg) {
        uni.showToast({
          title: res.msg,
          icon: 'none',
          duration: 2000
        });
      }
    }
  } catch (error) {
    console.error('获取订单列表失败:', error);

    if (!loadMore) {
      state.pagination.data = [];
      state.pagination.total = 0;
    }
    state.loadStatus = 'noMore';

    uni.showToast({
      title: '加载失败，请稍后重试',
      icon: 'none',
      duration: 2000
    });
  }
}

// 切换标签
function onTabsChange(e) {
  state.currentTab = e.index;
  state.pagination.current_page = 1;
  getOrderList(1, false);
}

// 加载更多
function loadmore() {
  if (state.loadStatus === 'more') {
    getOrderList(state.pagination.current_page + 1, true);
  }
}

// 触底加载
onReachBottom(() => {
  loadmore();
});

// 查看订单详情
function onOrderDetail(orderId) {
  sheep.$router.go('/pages/catering/order-detail', {
    orderId: orderId
  });
}

// 去支付
function onPay(order) {
  sheep.$router.go('/pages/catering/order-pay', {
    orderId: order.orderId
  });
}

// 获取订单商品列表
function getOrderProducts(order) {
  if (!order || !order.products) return [];
  return Array.isArray(order.products) ? order.products : [];
}

// 获取商品名称
function getProductName(product) {
  return product.name || product.productName || product.title || '商品';
}

// 获取商品图片
function getProductImage(product) {
  return product.image || product.pic || product.productImage || 'https://static.cdn.23kfc.com/img/default-product.png';
}

// 获取商品规格文本
function getProductSpec(product) {
  // 优先使用specsText
  if (product.specsText) return product.specsText;

  // 尝试从selected字段生成规格文本
  if (product.selected && Array.isArray(product.selected)) {
    return product.selected.map(s => s.name || s.value).filter(Boolean).join('/');
  }

  // 尝试从selectedSpecs对象生成规格文本
  if (product.selectedSpecs && typeof product.selectedSpecs === 'object') {
    return Object.values(product.selectedSpecs).filter(Boolean).join('/');
  }

  return '';
}

// 获取商品价格
function getProductPrice(product) {
  return product.price || product.salePrice || product.productPrice || 0;
}

// 获取商品数量
function getProductCount(product) {
  return product.count || product.quantity || product.num || 1;
}

// 获取商品总数
function getTotalCount(products) {
  if (!products || !Array.isArray(products)) return 0;
  return products.reduce((total, item) => total + getProductCount(item), 0);
}

// 格式化价格
function formatPrice(price) {
  return (price || 0).toFixed(2);
}

// 格式化时间
function formatTime(time) {
  if (!time) return '';

  // 处理时间字符串
  const date = new Date(time);

  // 格式化为 YYYY-MM-DD HH:mm:ss
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

// 获取订单状态名称
function getOrderStatusName(status) {
  const statusMap = {
    0: '等待支付',
    1: '待核销',
    3: '已出码',
    6: '订单退款',
    7: '超时未付',
    8: '订单成功(部分退款)',
    12: '配送中',
  };
  return statusMap[status] || '未知状态';
}

// 订单状态颜色
function formatOrderColor(status) {
  const colorMap = {
    0: 'warning-color',
    1: 'info-color',
    3: 'success-color',
    6: 'danger-color',
    7: 'disabled-color',
    8: 'success-color',
    12: 'info-color',
  };
  return colorMap[status] || '';
}
</script>

<style lang="scss" scoped>
.order-list-card-box {
  margin-bottom: 20rpx;
}

.order-card-header {
  height: 80rpx;
  border-bottom: 2rpx solid #f7f7f7;

  .order-no {
    font-size: 26rpx;
    color: #999;
  }
}

.store-info {
  border-bottom: 2rpx solid #f7f7f7;

  .store-name {
    font-size: 28rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 8rpx;
  }

  .order-time {
    font-size: 24rpx;
    color: #999;
  }
}

.goods-scroll-list {
  max-height: 400rpx; // 最大高度,超过后可滚动
  overflow-y: auto;
}

.goods-item {
  .goods-img {
    width: 160rpx;
    height: 160rpx;
    border-radius: 10rpx;
    flex-shrink: 0;
  }

  .goods-content {
    .goods-title {
      font-size: 28rpx;
      color: #333;
      line-height: 1.4;
    }

    .goods-spec {
      font-size: 24rpx;
      color: #999;
    }

    .goods-footer {
      .goods-price {
        font-size: 28rpx;
        color: #c7000b;
        font-weight: bold;
      }

      .goods-num {
        font-size: 24rpx;
        color: #999;
      }
    }
  }
}

.pay-box {
  padding-bottom: 20rpx;

  .discounts-title {
    font-size: 26rpx;
  }

  .discounts-money {
    font-size: 32rpx;
    font-weight: bold;
  }

  .pay-color {
    color: #c7000b;
  }
}

.order-card-footer {
  height: 100rpx;
  border-top: 2rpx solid #f7f7f7;

  .apply-btn {
    width: 160rpx;
    height: 60rpx;
    border: 2rpx solid #e5e5e5;
    border-radius: 30rpx;
    font-size: 26rpx;
    color: #999;
    margin-left: 20rpx;
  }

  .tool-btn {
    width: 160rpx;
    height: 60rpx;
    border-radius: 30rpx;
    font-size: 26rpx;
    color: #fff;
    margin-left: 20rpx;
  }
}

.warning-color {
  color: #faad14;
}

.info-color {
  color: #1890ff;
}

.success-color {
  color: #52c41a;
}

.danger-color {
  color: #f5222d;
}

.disabled-color {
  color: #999;
}

.ml-auto {
  margin-left: auto;
}

.empty-products {
  text-align: center;
  border-bottom: 2rpx solid #f7f7f7;

  .empty-text {
    font-size: 26rpx;
    color: #999;
  }
}
</style>

